package com.sx.manage.service.relation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sx.manage.service.company.IMBaseCompanyService;
import com.sx.manage.service.consumer.IMBaseSystemConsumerInfoService;
import com.sx.manage.service.consumer.IMSystemConsumerInfoService;
import com.sx.manage.service.function.IMBaseFunctionButtonInfoService;
import com.sx.manage.service.function.IMBaseFunctionInfoService;
import com.sx.manage.service.role.IMBaseRoleInformationService;
import com.sx.model.constants.MDataStatusType;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.consumer.MCompanyForm;
import com.sx.model.manage.mybatis.form.function.MFunctionButtonInfoForm;
import com.sx.model.manage.mybatis.form.function.MFunctionInfoForm;
import com.sx.model.manage.mybatis.form.role.MRoleForm;
import com.sx.model.manage.mybatis.vo.company.MCompanyVO;
import com.sx.model.manage.mybatis.vo.consumer.MSystemConsumerInfoVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.function.MFuncButtonVO;
import com.sx.model.manage.mybatis.vo.function.MFunctionInfoVO;
import com.sx.model.manage.mybatis.vo.relation.MRelationConfigVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.role.MRoleVO;

/**
 * 关系 模块 web-service
 * 
 * @author lenovo
 *
 */
@Service("webRelationServiceImpl")
public class MWebRelationServiceImpl {
	/**
	 * 日志
	 */
	private Logger _log = LoggerFactory.getLogger(this.getClass());

	// 角色 service
	@Resource(name = "mBaseRoleInfoServiceImpl")
	private IMBaseRoleInformationService mBaseRoleInfoServiceImpl;

	// 系统关系 service
	@Resource(name = "mBaseRelationConfigServiceImpl")
	public IMBaseRelationConfigService mBaseRelationConfigServiceImpl;
	// 模块信息
	@Resource(name = "mBaseFunctionInfoServiceImpl")
	private IMBaseFunctionInfoService mBaseFunctionInfoServiceImpl;
	// 系统用户
	@Resource(name = "systemConsumerInfoServiceImpl")
	private IMSystemConsumerInfoService systemConsumerInfoServiceImpl;

	// 系统用户
	@Resource(name = "mBaseSystemConsumerInfoServiceImpl")
	private IMBaseSystemConsumerInfoService mBaseSystemConsumerInfoServiceImpl;
	// 按钮信息
	@Resource(name = "mBaseFunctionButtonInfoServiceImpl")
	private IMBaseFunctionButtonInfoService mBaseFunctionButtonInfoServiceImpl;

	@Resource(name = "mBaseCompanyServiceImpl")
	private IMBaseCompanyService mBaseCompanyServiceImpl;

	public Logger get_log() {
		return _log;
	}

	public void set_log(Logger _log) {
		this._log = _log;
	}

	public IMSystemConsumerInfoService getSystemConsumerInfoServiceImpl() {
		return systemConsumerInfoServiceImpl;
	}

	public void setSystemConsumerInfoServiceImpl(IMSystemConsumerInfoService systemConsumerInfoServiceImpl) {
		this.systemConsumerInfoServiceImpl = systemConsumerInfoServiceImpl;
	}

	/**
	 * 角色配置权限，展示模块信息列表
	 * 
	 * @param roleId
	 * @param roleType
	 * @return
	 */
	public ResultListVO<MFunctionInfoVO> role2listForConfig(Long roleId, String roleType) {
		_log.debug("角色配置权限，展示模块信息列表 service 方法调用roleId={},roleType={}", roleId, roleType);
		ResultListVO<MFunctionInfoVO> listResult = new ResultListVO<>();
		// 获取角色
		MRoleVO role_ = this.mBaseRoleInfoServiceImpl.queryById(roleId).getObjVo();

		String[] relationTypeArr = new String[] { MSystemConstants.RELA_ROLE_FUNCTION, MSystemConstants.RELA_ROLE_FUNCTION_BUTTON };
		// 获取关系列表
		List<MRelationConfigVO> relaList = mBaseRelationConfigServiceImpl.queryListByRole(roleId, relationTypeArr);
		// configVO类转buttonId
		List<Long> relationButtonList = createButtonRelaList(relaList);
		MFunctionInfoForm form = new MFunctionInfoForm();
		form.setData_status(MDataStatusType.DATA_AVAILABLE);
		// 公司与角色
		if (MSystemConstants.ROLE_TYPE_COMPANY.equals(role_.getRole_type())) {
			form.setSystem_code(MSystemConstants.MODULE_COMPANY_);
			// 系统用户与角色
		} else if (MSystemConstants.ROLE_TYPE_USER_CENTER.equals(role_.getRole_type())) {
			form.setSystem_code(MSystemConstants.MODULE_USER_CENTER);
		}
		//
		form.setNeedSearchDetail(true);
		_log.debug("查询按钮信息标示设置为true，开始查询数据form={}", form);
		// 获取模块数据
		List<MFunctionInfoVO> functinListAll = this.mBaseFunctionInfoServiceImpl.get_functionList(form).getData();
		// 计算模块的子节点
		List<Long> numberList = new ArrayList<>();
		for (MFunctionInfoVO vo : functinListAll) {
			if (null != vo.getPid()) {
				numberList.add(vo.getPid());
			}else {
				vo.setNodeNum(1);
			}
		}
		// 获取角色配置的模块
		Map<Long, MFunctionInfoVO> functinMap = mBaseFunctionInfoServiceImpl.get_map_function_by_role_id(new Long[] { roleId });
		// 配置的模块置为选中状态
		List<MFuncButtonVO> detailList = null;
		MFunctionButtonInfoForm buttonForm = null;
		for (MFunctionInfoVO fun_ : functinListAll) {
			// 勾选 按钮
			buttonForm = new MFunctionButtonInfoForm();
			buttonForm.setFunction_id(fun_.getId());
			// 勾选
			if (null != functinMap.get(fun_.getId())) {
				fun_.setCheck_status(MSystemConstants.NO_);
			}
			detailList = mBaseFunctionButtonInfoServiceImpl.queryButtonList(buttonForm).getData();
			fun_.setDetailList(detailList);
			if (null == detailList) {
				continue;
			}
			// 勾选按钮
			for (MFuncButtonVO buttonVO : detailList) {
				if (relationButtonList.indexOf(buttonVO.getId()) >= 0) {
					buttonVO.setCheck_status(MSystemConstants.NO_);
				}
			}
		}
		listResult.setData(functinListAll);
		return listResult;
	}

	/** 数据关系 list to list **/
	public List<Long> createButtonRelaList(List<MRelationConfigVO> relaList) {
		List<Long> relationButtonList = new ArrayList<>(relaList.size());
		for (MRelationConfigVO configVO : relaList) {
			relationButtonList.add(configVO.getButton_id());
		}
		return relationButtonList;
	}

	/**
	 * 获取接入商配置的角色
	 * 
	 * @param supplier_id
	 * @return
	 */
	public ResultListVO<MRoleVO> getRoleListForBusinessConfig(Long business_id) {

		if (business_id == null) {
			_log.debug(" 方法 getRoleListForSupplierConfig 调用 参数为空 ");
			return new ResultListVO<>("m.parameter.is.null");
		}
		_log.debug(" 方法 getRoleListForSupplierConfig 调用 supplier_id=" + business_id);
		try {
			// 未完成（查询接入商数据）
			// 用户关系
			_log.debug("查询供应商的关系数据");
			ResultListVO<MRelationConfigVO> reslut = this.mBaseRelationConfigServiceImpl.queryListByConsumer(business_id, MSystemConstants.RELA_BUSINESS_ROLE, null);
			if (null == reslut.getData()) {
				return new ResultListVO<>("sj.m.common.query.error");
			}
			List<MRelationConfigVO> userRela = reslut.getData();

			// 角色
			MRoleForm form = new MRoleForm();
			// userNature为系统关系用户（供应商暂时列为系统数据）
			form.setRole_type(MSystemConstants.ROLE_TYPE_USER_CENTER);

			ResultListVO<MRoleVO> roleListResult = new ResultListVO<>();

			// 获取可以配置的角色信息
			_log.debug("查询供应商可以配置的角色");
			List<MRoleVO> roleList = this.mBaseRoleInfoServiceImpl.queryListForConfig(form);

			if (null == roleList) {
				return new ResultListVO<>("sj.m.sys.null.role.error");
			}
			String module_system = MSystemConstants.MODULE_SYSTEM_NAME + "-";
			// 角色勾选状态
			for (MRoleVO roleVO : roleList) {
				roleVO.setRole_name(module_system + roleVO.getRole_name());
				for (MRelationConfigVO relationVO : userRela) {
					if (relationVO.getRole_id() != null && relationVO.getRole_id().equals(roleVO.getId())) {
						roleVO.setCheck_status(MSystemConstants.NO_);
					}
				}
			}
			roleListResult.setData(roleList);
			_log.debug("方法执行完成返回");
			return roleListResult;
		} catch (Exception e) {
			_log.error("获取接入商角色失败error={}", e);
		}
		return null;
	}

	/**
	 * 系统用户分配权限
	 * 
	 * @param consumer_id
	 * @return
	 */
	public ResultListVO<MRoleVO> listRoleForSysConsumerConfig(Long consumer_id, MConsumerLoginVO loginConsumer) {
		try {
			MSystemConsumerInfoVO svo = this.mBaseSystemConsumerInfoServiceImpl.queryById(consumer_id).getObjVo();
			if (null == svo) {
				return new ResultListVO<>("m.user.not.exist");
			}

			// 用户关系
			ResultListVO<MRelationConfigVO> reslut = this.mBaseRelationConfigServiceImpl.queryListByConsumer(consumer_id, MSystemConstants.RELA_SYSTEM_CONSUMER_ROLE, loginConsumer);
			if (null == reslut.getData()) {
				return new ResultListVO<>("sj.m.common.query.error");
			}
			List<MRelationConfigVO> userRela = reslut.getData();
			List<Long> relationRoleList = new ArrayList<>(userRela.size());
			for (MRelationConfigVO configVO : reslut.getData()) {
				relationRoleList.add(configVO.getRole_id());
			}
			// 角色
			MRoleForm form = new MRoleForm();
			// userNature为系统关系用户
			form.setRole_type(MSystemConstants.ROLE_TYPE_USER_CENTER);

			ResultListVO<MRoleVO> roleListResult = new ResultListVO<>();

			// 获取可以配置的角色信息
			List<MRoleVO> roleList = this.mBaseRoleInfoServiceImpl.queryListForSysConfig(svo, form);

			if (null == roleList) {
				return new ResultListVO<>("sj.m.sys.null.role.error");
			}
			// 角色勾选状态
			for (MRoleVO roleVO : roleList) {
				if (relationRoleList.indexOf(roleVO.getId())>=0) {
					roleVO.setCheck_status(MSystemConstants.NO_);
				}
			}
			roleListResult.setData(roleList);
			return roleListResult;
		} catch (Exception e) {
			_log.error("系统用户分配权限error={}", e);
		}
		return null;
	}

	public ResultListVO<MRoleVO> rolePage(MRoleForm form, MConsumerLoginVO loginConsumer) {
		ResultListVO<MRoleVO> result = this.mBaseRoleInfoServiceImpl.queryPage(form, loginConsumer);
		if (null != result.getData()) {
			for (MRoleVO roleVO : result.getData()) {
				if (null != roleVO.getCompany_id()) {
					MCompanyForm companyForm = new MCompanyForm(roleVO.getCompany_id());
					ResultObjectVO<MCompanyVO> resiltVO = mBaseCompanyServiceImpl.search_byIds(companyForm);

					roleVO.setCompany_name(resiltVO.getObjVo().getCompany_name());
				}
			}
		}
		return result;
	}
}
